import { View, Text, ViewProps } from "@tarojs/components";
import { TValue, Option } from "@/types";
import "./index.less";

type Props = {
  options?: Option[];
  values: TValue[];
  onChange?: (value: TValue[]) => void;
  isRadio?: boolean;
  isScroll?: boolean;
  childStyle?: React.CSSProperties;
  disabled?: boolean;
} & ViewProps;
const TagCheckbox = ({
  options = [],
  values = [],
  onChange,
  isRadio,
  childStyle = {},
  disabled = false,
  className = "",
  ...others
}: Props) => {
  const handleChange = (value: TValue) => {
    const checked = values.includes(value);
    let newValue: TValue[] = [];

    if (isRadio) {
      if (!checked) {
        newValue = [value];
      }
    } else {
      // 多选
      if (checked) {
        newValue = values.filter((item) => item !== value);
      } else {
        newValue = [...values, value];
      }
    }

    onChange?.(newValue);
  };

  return (
    <View className={`tag-checkbox ${className}`} {...others}>
      {options.length > 0 &&
        options.map((item) => {
          const checked = values.includes(item.value);
          return (
            <View
              className={`tag-item ${checked ? "checked" : ""} ${
                disabled ? "disabled" : ""
              }`}
              style={childStyle}
              key={item.value}
              onClick={() => {
                if (disabled) {
                  return;
                }
                handleChange(item.value);
              }}
            >
              <Text>{item.label}</Text>
              {item.sub && <View className="tag-item-sub">{item.sub}</View>}
            </View>
          );
        })}
    </View>
  );
};

export default TagCheckbox;
